package com.igbeok.miscellaneous.concurrency.notify;

public class NotifyTest {

	private String flag = "true";

	class NotifyThread extends Thread {
		public NotifyThread(String name) {
			super(name);
		}

		public void run() {
			try {
				sleep(3000);// 3秒后通知
			} catch (Exception e) {
				throw new RuntimeException(e);
			}

			flag = "false";
			flag.notify();
		}
	}

	class WaitThread extends Thread {
		public WaitThread(String name) {
			super(name);
		}

		public void run() {
			while (!"false".equals(flag)) {
				System.out.println(getName() + " 开始等待");
				long waitTime = System.currentTimeMillis();
				try {
					flag.wait();
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				waitTime = System.currentTimeMillis() - waitTime;
				System.out.println("等待时间: " + waitTime);
			}
			System.out.println("等待结束");
		}
	}

	public static void main(String[] args) {
		System.out.println("Main thread running");
		NotifyTest test = new NotifyTest();
		NotifyThread notifyThread = test.new NotifyThread("notify01");
		WaitThread waitThread01 = test.new WaitThread("waiter01");
		WaitThread waitThread02 = test.new WaitThread("waiter02");
		WaitThread waitThread03 = test.new WaitThread("waiter03");
		notifyThread.start();
		waitThread01.start();
		waitThread02.start();
		waitThread03.start();
	}
}
